// 负责登录与注册
const express = require('express');
const router = express.Router();
const passport = require('passport');

const Profile = require ("../../models/Profile");

// POST api/profiles/add 创建信息接口 private
router.post('/add', passport.authenticate('jwt', {session: false}), (req, res) => {
   const profileFields = {};
   if(req.body.type) profileFields.type = req.body.type;
   if(req.body.describe) profileFields.type = req.body.describe;
   if(req.body.income) profileFields.type = req.body.income;
   if(req.body.expend) profileFields.type = req.body.expend;
   if(req.body.cash) profileFields.type = req.body.cash;
   if(req.body.remark) profileFields.type = req.body.remark;

   new Profile(profileFields).save().then((profile) => {
       res.json(profile);
   })
});

// GET api/profiles 获取所有信息 private
router.get('/', passport.authenticate('jwt', {session: false}), (req, res) => {
   Profile.find().then(profile => {
       if(!profile) {
           return res.status(404).json('没有任何内容');
       }
       res.json(profile)
   }).catch(err => res.status(404).json(err));
});

// GET api/profiles/:id 获取单个信息 private
router.get('/:id', passport.authenticate('jwt', {session: false}), (req, res) => {
    Profile.findOne({_id:req.params.id}).then(profile => {
        if(!profile) {
            return res.status(404).json('没有任何内容');
        }
        res.json(profile)
    }).catch(err => res.status(404).json(err));
});

// POST api/profiles/edit 编辑信息接口 private
router.post('/edit/:id', passport.authenticate('jwt', {session: false}), (req, res) => {
    const profileFields = {};
    if(req.body.type) profileFields.type = req.body.type;
    if(req.body.describe) profileFields.type = req.body.describe;
    if(req.body.income) profileFields.type = req.body.income;
    if(req.body.expend) profileFields.type = req.body.expend;
    if(req.body.cash) profileFields.type = req.body.cash;
    if(req.body.remark) profileFields.type = req.body.remark;

    Profile.findOneAndUpdate({_id:req.params.id}, {$set:profileFields}, {new: true}).then(profile => {
        res.json(profile);
    })
});

// POST api/profiles/delete/:id 删除信息接口 private
router.post('/delete/:id', passport.authenticate('jwt', {session: false}), (req, res) => {
    Profile.findOneAndRemove({_id: req.params.id}).then(profile => {
        profile.save.then(profile => {
            res.json(profile);
        }).catch(err => res.status(404).json('删除失败!'))
    })
});

module.exports = router;